import scopt.test.common
from scopt.mpu.security.db_registry.handlers import authenticate_login_password
from scopt.test.common import DEFAULT_LOGIN
from scopt.test.common import DEFAULT_PASSWORD


class AuthenticateLoginPassword(scopt.test.common.ScoptTest):
    '''Authenticate login password tests
    MPU should:

    1. test_valid_user
        send auth request with valid username and password
    2. test_invalid_user
        send auth request with invalid username and valid password
    3. test_invalid_password
        send auth request with valid username and invalid password
    4. test_invalid_password_invalid_user
        send auth request with invalid username and invalid password
    '''
    def test_valid_user(self):
        handler = authenticate_login_password.handle
        token = handler.TOKEN()
        token['login'] = DEFAULT_LOGIN
        token['password'] = DEFAULT_PASSWORD
        response = self.send_request(self.dummy_request(), token)

        self.assertEqual(response['resh']['status'], 'OK')
        self.assertIsNotNone(response['resd']['token'])
        self.assertEqual(response['resd']['principal']['username'],
                         'Administrator')
        self.assertEqual(response['resd']['principal']['login'], 'ADMIN')

    def test_invalid_user(self):
        handler = authenticate_login_password.handle
        token = handler.TOKEN()
        token['login'] = 'non-existing_user'
        token['password'] = DEFAULT_PASSWORD
        response = self.send_request(self.dummy_request(),
                                     token,
                                     pass_interrupts=True)

        self.__assert_wrong_data(response)

    def test_invalid_password(self):
        handler = authenticate_login_password.handle
        token = handler.TOKEN()
        token['login'] = 'non-existing_user'
        token['password'] = 'wrong_password'
        response = self.send_request(self.dummy_request(),
                                     token,
                                     pass_interrupts=True)

        self.__assert_wrong_data(response)

    def test_invalid_password_invalid_user(self):
        handler = authenticate_login_password.handle
        token = handler.TOKEN()
        token['login'] = 'non-existing_user'
        token['password'] = 'wrong_password'
        response = self.send_request(self.dummy_request(),
                                     token,
                                     pass_interrupts=True)

        self.__assert_wrong_data(response)

    def __assert_wrong_data(self, response):
        self.assertEqual(response['resh']['status'], 'INT')
        self.assertIsNotNone(response['resd']['text'])
        self.assertEqual(response['resd']['reason'], 'EXCEPTION')
        self.assertEqual(response['resd']['code'],
                         'security.invalid.login.password')
